import { getInfo, login } from '@/api/user'
import { Message } from 'element-ui'
import { getToken, removeToken, setToken } from '@/utils/auth'
import router from '@/router'
import { resetRouter } from '@/router/index'
const state = {
  userItem: {},
  token: getToken() || ''
}

const mutations = {
  logout(state) {
    state.userItem = {}
    state.token = ''
    removeToken()
    resetRouter()
  },
  getUseritem(state, newUser) {
    state.userItem = newUser
  },
  getToken(state, newToken) {
    // 存到VUEX
    state.token = newToken
    // 存到Cookie
    setToken(newToken)
  }
}

const actions = {
  logout(context) {
    context.commit('logout')
  },
  async getUser(context) {
    const res = await getInfo()
    // console.log(res.data)
    context.commit('getUseritem', res.data)
    return res.data
  },

  async login(context, payloap) {
    const res = await login(payloap)
    const token = res.data
    context.commit('getToken', token)
    if (res.success) {
      Message.success('登录成功')
      router.push('/')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
